package com.gin.kotlin.gf2gamecommunity.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import com.gin.kotlin.form.ItemExchangeForm
import com.gin.kotlin.gf2gamecommunity.app.App
import com.gin.kotlin.gf2gamecommunity.base.livedata.CachedLiveData
import com.gin.kotlin.response.ListData
import com.gin.kotlin.response.Res
import com.gin.kotlin.response.item.ExchangeableItem
import kotlinx.coroutines.delay
import retrofit2.awaitResponse

class ExchangeItemViewModel : ViewModel() {

    val exchangeList = CachedLiveData<Res<ListData<ExchangeableItem>>, List<ExchangeableItem>>(
        requestMethod = { App.INSTANCE.api.itemApi.getExchangeList() },
        bodyTransform = { it.data?.list },
    )

    /**
     * 执行兑换
     * @param id 道具ID
     * @param count 兑换数量
     * @param onSuccess 执行成功一次的回调
     * @param onCompleted 全部执行完毕的回调
     */
    suspend fun exchange(id: Int, count: Int, onSuccess: (success: Int) -> Unit, onCompleted: suspend (success: Int) -> Unit = {}) {
        var success = 0
        for (i in 0 until count) {
            try {
                val response = App.INSTANCE.api.itemApi.exchange(ItemExchangeForm(id)).awaitResponse()
                val message = response.body()?.message ?: response.message()
                Log.i(TAG, "id: $id, message: $message")
                success++
                onSuccess(success)
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }
        onCompleted(success)
    }

    /**
     * 兑换列表中的所有可兑换道具，执行前需自行判断积分是否足够兑换所有道具
     * @param list 道具列表
     * @param onItemSuccess 每次进度更新的回调
     */
    suspend fun exchangeAll(
        list: List<ExchangeableItem>? = exchangeList.liveData.value,
        onItemSuccess: (item: ExchangeableItem, success: Int) -> Unit = { _, _ -> }
    ) {
        val items = list?.takeIf { it.isNotEmpty() }?.filter { it.exchangeable() }
        if (items == null) {
            return
        }
        // 降序排列
        items.forEach { item ->
            Log.i(TAG, "兑换 ${item.itemName} ${item.exchangeableCount()} 个")
            exchange(item.exchangeId, item.exchangeableCount(), onSuccess = { success -> onItemSuccess(item, success) })
            delay(200)
        }
        exchangeList.fetch(true)
        delay(200)
    }

    companion object {
        private val TAG = ExchangeItemViewModel::class.java.simpleName
    }
}